import os  
import json  
from coach.coach import Coach  
import time  
# 查询SQLIte3的数据库中某个表的最新的记录的oid字段
import sqlite3  
from typing import Tuple, Dict, List, Any  
import copy  

class History:
    def __init__(self):
        # 获取项目根目录下的temp文件夹路径  
        self.base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))  
        self.temp_dir = os.path.join(self.base_dir, 'temp')  
        self.history_file_path = os.path.join(self.temp_dir, 'history.json')  
        # 确保temp文件夹存在  
        os.makedirs(self.temp_dir, exist_ok=True)  
        # 获取当前时间的时间戳  
        self.current_timestamp = int(time.time())  
        # print(f"当前时间的时间戳是：{self.current_timestamp}")  
        # 假设Coach是一个已经定义好的类，这里创建一个实例  
        self.coach_instance = Coach()  # 注意：我更改了变量名以避免混淆  
          
        # 这些测试变量可能不应该放在__init__方法中，除非它们有特定的用途  
        self.test_timestamp = 1722396235  
        self.test_max_oid = 112845953960330  
          
        # 数据库路径  
        self.database_path = os.path.join(os.path.dirname(__file__), '..', 'coach', 'database', 'coach.db')  
        # print("database file path", self.database_path)  
        # 连接数据库  
        self.conn = sqlite3.connect(self.database_path)  
        # 创建一个Cursor对象  
        self.cursor = self.conn.cursor()  
        # 注意：这里将history设置为None可能不是最佳实践，除非你有特定的用途  
        self.history = None  
    def login(self):
        self.coach_instance.login() 
    def get_history(self,timestamp = None, oid = None):
        """获取用户历史记录 
        注意,这个方法只能获取20条最近的浏览记录而不是所有的.
        """         
        self.history : 'dict' = self.coach_instance.fetch_user_history(view_at = timestamp,max = oid)  
        #history : 'dict' = instance.fetch_user_history() 
        # print("历史记录：", history)  
        # self.save_history_to_local(self.history)
        return self.history
    def save_history_to_local(self,history):
        # 将历史记录字典保存到temp文件夹中的history.json文件  
        with open(self.history_file_path, 'w', encoding='utf-8') as f:  
            json.dump(history, f, ensure_ascii=False, indent=4)  
        # print(f"历史记录已保存到 {self.history_file_path}")
    def get_latest_history_oid(self) -> str :
        # 查询某个表（例如'my_table'）的最新记录的oid  
        self.cursor.execute("SELECT oid FROM video_records ORDER BY view_at DESC LIMIT 1;")  
        # 获取查询结果  
        latest_record_oid = self.cursor.fetchone()  
        latest_oid_str = str(latest_record_oid[0])  
        if latest_record_oid:  
            # print(f"最新记录的oid是: {latest_record_oid[0]}") 
            return latest_oid_str 
        else:  
            print("表是空的。")  
    def get_current_timestamp(self):
        self.current_timestamp = int(time.time()) 
        return self.current_timestamp
    def get_result_lastitem_oid(self,history):
        # 似乎可以直接按照操作JSON的方法直接操作Dict
        if history:
            last_member = history["list"][-1]  
            item_oid = last_member['history']['oid']
            # print(last_member)
            return item_oid
    def save_to_database(self,history : 'dict'):
        # 相当于API的原始结果
        # 遍历列表中的每个记录，并将其插入到数据库中  
        for record in history["list"]:  
            try:
                self.cursor.execute('''  
                INSERT INTO video_records (  
                    title,  
                    long_title,  
                    cover,   
                    uri,  
                    oid,  -- history 字典的字段之一  
                    bvid,  
                    page, 
                    cid,   
                    author_name,  
                    author_face,  
                    author_mid,  
                    view_at,  
                    progress,  
                    duration,  
                    is_finish,  
                    is_fav,  
                    tag_name,  
                    live_status  
                )  
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)  
                ''', (  
                    record["title"],  
                    record["long_title"],  
                    record["cover"],  
                    record["uri"],  
                    record["history"]["oid"],  
                    record["history"]["bvid"],  
                    record["history"]["page"],  
                    record["history"]["cid"],  
                    record["author_name"],  
                    record["author_face"],  
                    record["author_mid"],  
                    record["view_at"],  
                    record["progress"],  
                    record["duration"],  
                    record["is_finish"],  
                    record["is_fav"],  
                    record["tag_name"],  
                    record["live_status"]  
                ))
            except KeyError as e:  
                print(f"缺少必要的键: {e}, 跳过记录: {record}")  
        self.conn.commit()  
        # print("观看历史记录已保存到数据库中！")
    def get_result_lastitem_timestamps(self,history):
        # 似乎可以直接按照操作JSON的方法直接操作Dict
        if history:
            try: 
                last_member = history["list"][-1]  
            except Exception as e:  
                print(f"An error occurred whwile processing history: {histry}")  
            last_timestamp = last_member['view_at']
            # print(last_timestamp)
            return last_timestamp
    def result_match_target_oid(self, histry: Dict[str, Any], target_oid: int) -> Tuple[bool, Dict[str, List[Dict[str, Any]]]]:  
        try:  
            # 创建一个histry的深拷贝  
            modified_histry = copy.deepcopy(histry)  
            
            # 在副本上进行操作  
            items = modified_histry.get('list', [])  
            for i, item in enumerate(items):  
                # 检查history中的oid是否与target_oid匹配  
                item_oid = item.get('history', {}).get('oid')
                # print("Item oid and target oid", item_oid , target_oid)
                if int(item_oid) == int(target_oid):  
                    # 如果匹配，删除该项及其后面的所有项（在副本中）  
                    print("匹配成功")
                    del items[i:]  
                    # 返回True和裁剪后的副本字典  
                    return True, modified_histry  
            # 如果没有匹配项，返回False和未修改的副本字典  
            return False, modified_histry  
        except Exception as e:  
            # 捕获到异常时打印错误信息和相关上下文  
            print(f"An error occurred while processing history: {histry}")  
            print(f"Exception: {e}")  
            # 在这里，你可以选择重新抛出异常，或者返回一个表示错误的元组（比如(False, None)）  
            # 但通常，重新抛出异常是更好的做法，因为它允许调用者处理错误  
            # raise  
    def update_history_from_last(self):
        # 从当前时间不断的加载历史数据到数据库中最新的
        # database_latest_OID = self.get_latest_history_oid()
        database_latest_OID = 36588448
        print("Latest OID", database_latest_OID)
        current_timestamp = self.get_current_timestamp()
        temp_timestamp = current_timestamp
        # 记录一次请求中最后一个Item的oid 初始化为空
        temp_oid = None
        continual_flag = True
        # return True
        while continual_flag:
            temp_history = self.get_history(timestamp= temp_timestamp, oid = temp_oid)
            # print(temp_history)
            try: 
                matched_result , cropped_temp_history = self.result_match_target_oid(temp_history,database_latest_OID)
            except Exception as e:  
                # 捕获到异常时打印错误信息和相关上下文  
                print(f"An error occurred while processing history ")  
                print(f"Exception: {e}")  
            if matched_result:
                print("命中历史记录结果", database_latest_OID)
                self.save_to_database(cropped_temp_history)
                return True # 结束请求
            else:
                self.save_to_database(temp_history)
                # 更新请求历史
                temp_timestamp = self.get_result_lastitem_timestamps(temp_history)
                temp_oid = self.get_result_lastitem_oid(temp_history)
                
    def __del__(self):
        # 在删除对象时关闭数据库连接和游标  
        if hasattr(self, 'cursor'):  
            self.cursor.close()  
        if hasattr(self, 'conn'):  
            self.conn.close()   

if __name__ == '__main__':
    instance = History()
    instance.login()
    instance.update_history_from_last()
    # print(instance.get_latest_history_oid())

